/**
 * FileName: EmployeeController
 * Author: Administrator
 * Date: 2018/11/19 18:29
 * Description: 执行RUCD,对所有员工
 */
package com.cym.controller;

import com.cym.bean.Employee;
import com.cym.service.EmployeeService;
import com.cym.utils.ComMsg;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;


    @RequestMapping("/find")
    @ResponseBody
    public ComMsg getEmployeesWithJson(@RequestParam(value = "",defaultValue = "1") Integer pages){
        //传入页码，每页的大小
        PageHelper.startPage(pages,5);
        List<Employee> employees = employeeService.find();
        //pageInfo里面封装了详细的分页信息，包括我们查询出来的数据，转入连续显示的页数
        PageInfo page = new PageInfo(employees,5);
        return ComMsg.success().add("pageInfo",page);
    }

    @RequestMapping(value = "/employee",method = RequestMethod.POST)
    @ResponseBody
    public ComMsg addEmployeeInfo(@Valid Employee employee, BindingResult result){
        if (result.hasErrors()){
            //校验失败，在模态框中显示校验失败的提示信息
            Map<String,Object> map = new HashMap<>();
            List<FieldError> fieldErrors = result.getFieldErrors();
            for (FieldError errors: fieldErrors) {
//                System.out.println("错误的字段名："+errors.getField());
//                System.out.println("错误信息："+errors.getDefaultMessage());
                map.put(errors.getField(),errors.getDefaultMessage());
            }
            return ComMsg.fail().add("valid_msg",map);
        }else{
            employeeService.addEmployeeInfo(employee);
            return ComMsg.success();
        }
    }

    @RequestMapping(value = "/checkUser",method = RequestMethod.POST)
    @ResponseBody
    public ComMsg checkUser(@RequestParam("empName") String empName){
        Boolean checkUser = employeeService.checkUser(empName);
        //先判断用户名是否是合法的用户名
        String regName = "(^[a-zA-Z0-9_-]{6,16}$)|(^[\\u2E80-\\u9FFF]{2,5}$)";
        if (!empName.matches(regName)){
            return ComMsg.fail().add("va_msg","用户名可以是2-5位中文或者6-16位英文和数字的组合");
        }
        //数据库重复校验
        if (checkUser){
            return ComMsg.success();
        }else{
            return ComMsg.fail().add("va_msg","用户名不可用");
        }
    }

    /**
     * 根据id查找员工的姓名
     * @param id
     * @return
     */
    @RequestMapping(value = "/find/{id}",method = RequestMethod.GET)
    @ResponseBody
    public ComMsg findEmpNameById(@PathVariable("id") Integer id){
        Employee empNameById = employeeService.findEmpNameById(id);
        return ComMsg.success().add("employee",empNameById);
    }

    @RequestMapping(value = "/find/{empId}",method = RequestMethod.PUT)
    @ResponseBody
    public ComMsg updateEmployee(Employee employee){
        employeeService.updateEmployee(employee);
        return ComMsg.success();
    }

    /**
     * 批量，单个删除数据
     * @param id
     * @return
     */
    @RequestMapping(value = "/find/{ids}",method = RequestMethod.DELETE)
    @ResponseBody
    public ComMsg deleteEmployee(@PathVariable("ids") String ids){
        if (ids.contains("-")){
            List<Integer> idList = new ArrayList<>();
            String[] idsArr = ids.split("-");
            for (String idArr:idsArr) {
                idList.add(Integer.parseInt(idArr));
            }
            employeeService.deleteBath(idList);
        }else {
           Integer id = Integer.parseInt(ids);
           employeeService.deleteEmployee(id);
        }

        return ComMsg.success();
    }

    //@RequestMapping("/find")
    public String findEmployees(@RequestParam(value = "",defaultValue = "1") Integer pages, Model model){

        //传入页码，每页的大小
        PageHelper.startPage(pages,5);
        List<Employee> employees = employeeService.find();
        //pageInfo里面封装了详细的分页信息，包括我们查询出来的数据，转入连续显示的页数
        PageInfo page = new PageInfo(employees,5);
        //将pageInfo查询出来的信息交给页面
        model.addAttribute("pageInfo",page);
        return "list";
    }

}
